import { parse } from 'querystring';
import moment from 'moment';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

/**
 * 日期格式化
 * @param dayStr yyyyMMdd格式字符串
 * @returns 格式化为yyyy-MM-dd
 */
export const dateFormat = (dateStr: string) => {
  if (!dateStr) {
    return '';
  }
  if (dateStr.length < 8) {
    return dateStr;
  }
  const year = dateStr.substring(0, 4);
  const month = dateStr.substring(4, 6);
  const day = dateStr.substring(6, 8);
  return `${year}-${month}-${day}`;
}

/**
 * 时间格式化
 * @param dayStr HHmmss格式字符串
 * @returns 格式化为HH:mm:ss
 */
export const timeFormat = (timeStr: string) => {
  if (!timeStr) {
    return '';
  }
  if (timeStr.length < 6) {
    return timeStr;
  }
  const h = timeStr.substring(0, 2);
  const m = timeStr.substring(2, 4);
  const s = timeStr.substring(4, 6);
  return `${h}:${m}:${s}`;
}

export const getDateTime = () => {
  const weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const week = moment().format('d');
  return moment().format(`YYYY年M月D日 ${weeks[parseInt(week)]}`);
}

export const getCurrentDate = () => {
  const cDate: Date = new Date();
  let cYear: number = cDate.getFullYear();
  // 月份0-11，会少1，所以这里需要加1
  let cMonth: number = cDate.getMonth() + 1;
  let cDay: number = cDate.getDate();
  const dateStr = `${cYear}${fillZero(cMonth)}${fillZero(cDay)}}`;
  return dateStr;
}

/**
   * 数字小于10时，左补一位0
   * @param num 数字
   * @returns 补0后的字符串
   */
function fillZero(num: number) {
  if (num < 10) {
    return '0' + num;
  }
  return num + '';
}

/**
 * 计算两个日期之间相差的天数
 *
 * @param startDate 开始日期
 * @param endDate 结束日期
 * @returns 相差的天数
 */
export const getTimeDiffOfDay = (startDate: string, endDate: string) => {
  // 将字符串转换为 Date 对象
  const start = new Date(startDate).getMilliseconds();
  const end = new Date(endDate).getMilliseconds();
  // 获取相差的毫秒数
  const timeDiff = Math.abs(end - start);
  // 计算天数、小时数、分钟数和秒数
  const days = Math.floor(timeDiff / (1000 * 3600 * 24));
  return days;
}

export const transform2moment = (srcDate: string, format: string) => {
  return moment(srcDate, format);
}
